<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class MessageController extends AppUserBaseC {

    //站内消息列表
    public function actionMsgList() {
        $model = new MessageModel();
        $offset = (int) $_GET['offset'];
        $num = (int) Yii::app()->request->getParam('num');
        $count = (int) count($model->findAll($model->where(array('userid' => $this->uid,))));
        if ($num <= 0 && $count !== 0) {
            $num = $count;
        } elseif($num <= 0) {
            $num = 20;
        }
        $criteria = $model->where(array('userid' => $this->uid, 'order' => "is_read asc,datetime desc"));
        $criteria->limit = $num;
        $criteria->offset = $offset;
        $msglist = $model->findAll($criteria);

        if (!empty($msglist)) {
            $data = array();
            foreach ($msglist as $p => $xx) {
                $data[$p]['nid'] = $xx->nid;
                $data[$p]['userid'] = $xx->userid;
                $data[$p]['typeid'] = $xx->typeid;
                $data[$p]['title'] = $xx->title;
                $data[$p]['is_read'] = $xx->is_read;
                $data[$p]['extend_params'] = unserialize($xx->extend_params);
                $data[$p]['sendname'] = $xx->sendname;
                $data[$p]['senduid'] = $xx->senduid;
                $data[$p]['datetime'] = $xx->datetime;
                MessageModel::model()->noticeRead($xx->nid, $this->uid);
            }
            $this->ajaxReturn(array('status' => 1, 'info' => '读取消息成功', 'count' => $count, 'detail' => $data,));
        }
        $this->ajaxReturn(array('status' => 1, 'info' => '信息为空', 'detail' => '', 'count' => 0));
    }

    //是否有新消息

    public function actionIsNew() {
        $model = new MessageModel();
        $count = (int) $model->getNoticeNoReadCount($this->uid);
        if (empty($count)) {
            $this->ajaxReturn(array('status' => 0, 'info' => '您没有未读消息!', 'count' => 0));
        } else {
            $this->ajaxReturn(array('status' => 1, 'info' => '您有' . $count . '条未读消息!', 'count' => $count));
        }
    }

    //标记为已读

    public function actionRead() {
        $model = new MessageModel();
        $nid = Yii::app()->request->getParam('nid');
        if ($model->noticeRead($nid)) {
            $this->ajaxReturn(array('status' => true, 'info' => '已标记为已读'));
        } else {
            $this->ajaxReturn(array('status' => false, 'info' => '标记为已读失败'));
        }
    }

    //删除消息

    public function actionDelete() {
        $model = new MessageModel();
        $nid = Yii::app()->request->getParam('nid');
        if ($model->noticeDel($this->uid, $nid)) {
            $this->ajaxReturn(array('status' => true, 'info' => '删除成功!'));
        } else {
            $this->ajaxReturn(array('status' => false, 'info' => '删除失败!'));
        }
    }

}
